import React, { forwardRef, useState, useImperativeHandle } from "react";
import "./index.css";
import { useControllableValue } from "ahooks";
import { useMergeState } from "../Calendar";

interface CalendarProps {
  value?: Date;
  defaultValue?: Date;
  onChange?: (date: Date) => void;
}
export interface CalendarRef {
  getDate: () => Date;
  setDate: (date: Date) => void;
}
const InternalCalendar: React.ForwardRefRenderFunction<
  CalendarRef,
  CalendarProps
> = (props, ref) => {
  // const [date, setDate] = useControllableValue(props, {
  //   defaultValue: new Date()
  // });
  const [date, setDate] = useMergeState(new Date(), props);

  // 上个月的第一天。
  const handlePrevMonth = () => {
    setDate(new Date(date.getFullYear(), date.getMonth() - 1, 1));
  };

  // 下个月的第一天。
  const handleNextMonth = () => {
    setDate(new Date(date.getFullYear(), date.getMonth() + 1, 1));
  };

  useImperativeHandle(ref, () => {
    return {
      getDate() {
        return date;
      },
      setDate(date: Date) {
        setDate(date);
      },
    };
  });

  const monthNames = [
    "一月",
    "二月",
    "三月",
    "四月",
    "五月",
    "六月",
    "七月",
    "八月",
    "九月",
    "十月",
    "十一月",
    "十二月",
  ];

  // month 是从 0 开始计数的，取值是 0 到 11
  // 当你 date 传 0 的时候，取到的是上个月的最后一天
  const daysOfMonth = (year: number, month: number) => {
    return new Date(year, month + 1, 0).getDate();
  };

  const firstDayOfMonth = (year: number, month: number) => {
    return new Date(year, month, 1).getDay();
  };

  const renderDates = () => {
    const days = [];

    const daysCount = daysOfMonth(date.getFullYear(), date.getMonth());
    const firstDay = firstDayOfMonth(date.getFullYear(), date.getMonth());

    for (let i = 0; i < firstDay; i++) {
      days.push(<div key={`empty-${i}`} className="empty">{
        new Date(date.getFullYear(), date.getMonth(), i - firstDay + 1).getDate()
      }</div>);
    }

    for (let i = 1; i <= daysCount; i++) {
      const clickHandler = () => {
        const curDate = new Date(date.getFullYear(), date.getMonth(), i);
        setDate(curDate);
      };
      if (i === date.getDate()) {
        days.push(
          <div key={i} className="day selected" onClick={() => clickHandler()}>
            {i}
          </div>
        );
      } else {
        days.push(
          <div key={i} className="day" onClick={() => clickHandler()}>
            {i}
          </div>
        );
      }
    }

    const currRow = Math.ceil(days.length / 7)
    const nextDays = currRow * 7 - days.length
    if (nextDays > 0) {
      for (let i = 0; i < nextDays; i++) {
        days.push(<div key={`empty-${i}-next`} className="empty">{
          new Date(date.getFullYear(), date.getMonth() + 1, i + 1).getDate()
        }</div>);      
      }
    }
    return days;
  };

  return (
    <div className="calendar">
      <div className="header">
        <button onClick={handlePrevMonth}>&lt;</button>
        <div>
          {date.getFullYear()} 年 {monthNames[date.getMonth()]}
        </div>
        <button onClick={handleNextMonth}>&gt;</button>
      </div>
      <div className="days">
        <div className="day">日</div>
        <div className="day">一</div>
        <div className="day">二</div>
        <div className="day">三</div>
        <div className="day">四</div>
        <div className="day">五</div>
        <div className="day">六</div>
        {renderDates()}
      </div>
    </div>
  );
};

const Calendar = forwardRef(InternalCalendar);
export default Calendar;
